//
//  collectionViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "collectionViewController.h"
#import "collectionTableViewCell.h"


#import "SchoolProfileViewController.h"
#import "AgencyDetailsViewController.h"
#import "CourseDetailsViewController.h"
#import "DrivateTutorDetailViewController.h"

static NSString *CellIdentifier = @"collectionTableViewCell";

@interface collectionViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}

@property (strong, nonatomic) IBOutlet UIView *navView;

@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *buttonOne;//学校
@property (strong, nonatomic) IBOutlet UIButton *buttonTwo;//机构
@property (strong, nonatomic) IBOutlet UIButton *buttonThree;//课程
@property (strong, nonatomic) IBOutlet UIButton *buttonFour;//家教

@property(nonatomic,strong)NSMutableArray * collectArray;


@end

@implementation collectionViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _collectArray = [NSMutableArray array];

    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
}

- (IBAction)COLLECTION:(UIButton *)sender {
    _pageNO=1;
    if (sender == _buttonOne) {
        _buttonOne.selected = YES;
        _buttonTwo.selected = NO;
        _buttonThree.selected = NO;
        _buttonFour.selected = NO;
    } else if (sender == _buttonTwo){
        _buttonOne.selected = NO;
        _buttonTwo.selected = YES;
        _buttonThree.selected = NO;
        _buttonFour.selected = NO;
        
    } else if (sender == _buttonThree){
        _buttonOne.selected = NO;
        _buttonTwo.selected = NO;
        _buttonThree.selected = YES;
        _buttonFour.selected = NO;
        
    } else if (sender == _buttonFour){
        _buttonOne.selected = NO;
        _buttonTwo.selected = NO;
        _buttonThree.selected = NO;
        _buttonFour.selected = YES;
        
        
    }
    [self.tableView.header beginRefreshing];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            if (_buttonOne.selected) {
                [self school];
            } else if (_buttonTwo.selected) {
                [self institutions];
            } else if (_buttonThree.selected) {
                [self course];
            } else if (_buttonFour.selected) {
                [self family];
            }
            
        });
    }];
      [self.tableView.header beginRefreshing];
    
}
//加载更多数据
- (void)loadMoreData{
    _pageNO = 1;
    if (self.collectArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            if (_buttonOne.selected) {
                [self school];
            } else if (_buttonTwo.selected) {
                [self institutions];
            } else if (_buttonThree.selected) {
                [self course];
            } else if (_buttonFour.selected) {
                [self family];
            }
        });
    }
    
}

#pragma mark - 我收藏的学校列表
- (void)school {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallCollectDeveloperList withHttpType:@"POST" withTag:JY_JY_myMallCollectDeveloperList];
}

#pragma mark - 我收藏的机构列表
- (void)institutions {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallCollectStoreList withHttpType:@"POST" withTag:JY_JY_myMallCollectStoreList];
}
#pragma mark - 我收藏课程列表
- (void)course {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallCollectGoodsList withHttpType:@"POST" withTag:JY_JY_myMallCollectGoodsList];
}
#pragma mark - 我收藏的家教列表
- (void)family {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lat"] forKey:@"lat"];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"lng"] forKey:@"lng"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_myMallCollectLecturerList withHttpType:@"POST" withTag:JY_JY_myMallCollectLecturerList];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return self.collectArray.count;
  
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    collectionTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[collectionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    cell.moneyLabel.hidden = NO;
    cell.distanceButton.hidden = NO;
    cell.moneyLabel.frame = flexibleFrame(CGRectMake(111, 34, 191, 21), NO);
    cell.detailLabel.frame = flexibleFrame(CGRectMake(111, 51, 202, 38), NO);
    if (_buttonOne.selected) {
        
        NSString * image = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"msdeImage"]];
        if (image && image.length>0 && ![self.collectArray[indexPath.row][@"msdeImage"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"msdeName"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"msdeContent"]];
        
        NSString * space = @"";
        CGFloat distance = [[NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"distance"]]floatValue];
        if (distance>=1000) {
            space = [NSString stringWithFormat:@" %.1fkm",distance/1000];
        }else{
            space = [NSString stringWithFormat:@" %ldm",100*((NSInteger)(distance/100+1))];
        }

        [cell.distanceButton setTitle:space forState:UIControlStateNormal];
        cell.moneyLabel.hidden = YES;
        cell.detailLabel.frame = flexibleFrame(CGRectMake(111, 34, 202, 38), NO);
    } else if (_buttonTwo.selected) {
        
        NSString * image = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mstoImage"]];
        if (image && image.length>0 && ![self.collectArray[indexPath.row][@"mstoImage"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mstoName"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mstoContent"]];
      
        NSString * space = @"";
        CGFloat distance = [[NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mstodDistance"]]floatValue];
        if (distance>=1000) {
            space = [NSString stringWithFormat:@" %.1fkm",distance/1000];
        }else{
            space = [NSString stringWithFormat:@" %ldm",100*((NSInteger)(distance/100+1))];
        }
        
        [cell.distanceButton setTitle:space forState:UIControlStateNormal];
        cell.moneyLabel.hidden = YES;
        cell.detailLabel.frame = flexibleFrame(CGRectMake(111, 34, 202, 38), NO);
    } else if (_buttonThree.selected){
        
        NSString * image = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mallGoods"][@"mgooImage"]];
        if (image && image.length>0 && ![self.collectArray[indexPath.row][@"mallGoods"][@"mgooImage"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mallGoods"][@"mgooName"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@元/小时",self.collectArray[indexPath.row][@"mallGoods"][@"mgooPrice"]];
        cell.detailLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mallGoods"][@"mgooContext"]];
        cell.distanceButton.hidden = YES;
        
    } else {
        NSString * image = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"image"]];
        if (image && image.length>0 && ![self.collectArray[indexPath.row][@"image"] isEqual:[NSNull null]]) {
            [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
        }
        cell.titleLabel.text = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"name"]];
        cell.moneyLabel.text = [NSString stringWithFormat:@"￥%@元/小时",self.collectArray[indexPath.row][@"price"]];
        
        [cell.distanceButton setTitle:[NSString stringWithFormat:@" %@m",self.collectArray[indexPath.row][@"distance"]] forState:UIControlStateNormal];
        
        NSString *mlsuNames = @"";
        NSArray *array = _collectArray[indexPath.row][@"mallLecturerSubjects"];
        for (int i = 0; i < array.count; i++) {
            NSString *mlsuName = [NSString stringWithFormat:@"%@",array[i][@"mlsuName"]];
            mlsuNames = [mlsuNames stringByAppendingString:mlsuName];
        }
        cell.detailLabel.text = mlsuNames;
    }
    
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_buttonOne.selected) {
        //学校详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"SchoolStoryboard" bundle:nil];
        SchoolProfileViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SchoolProfile"];
        page.schoolId = _collectArray[indexPath.row][@"msdeId"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];
        
    } else if (_buttonTwo.selected) {
        //机构详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
        AgencyDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AgencyDetails"];
        
        page.mstoId = self.collectArray[indexPath.row][@"mstoId"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];
        
    } else if (_buttonThree.selected) {
        //课程详情
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"TeachStoryboard" bundle:nil];
        CourseDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"CourseDetails"];
        
        page.mgooId = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mallGoodsId"]];
         page.mstoId = [NSString stringWithFormat:@"%@",self.collectArray[indexPath.row][@"mgooStoreId"]];
        [[Common getNavigation] pushViewController:page];
        
    } else if (_buttonFour.selected) {
        //家教详情
        
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeTeachStoryboard" bundle:nil];
        DrivateTutorDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"DrivateTutorDetail"];
        
        page.mexpId = _collectArray[indexPath.row][@"id"];
        page.backBlock = ^(){};
        [[Common getNavigation] pushViewController:page];
    }
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag==JY_JY_myMallCollectDeveloperList || tag==JY_JY_myMallCollectStoreList || tag==JY_JY_myMallCollectGoodsList || tag==JY_JY_myMallCollectLecturerList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.collectArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.collectArray addObject:entity];
                }
                
                [_tableView reloadData];
                
            });
        }
    }
        
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    [self dismissWaitDialog];
    
    
}

@end
